package com.jmu.edu.IMApplication;

import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import com.jmu.edu.IMApplication.event.FriendNotificationRefresh;
import com.jmu.edu.IMApplication.net.bean.FriendInvite;
import com.jmu.edu.IMApplication.utils.FriendUtils;
import com.jmu.edu.IMApplication.utils.MsgUtils;
import com.jmu.edu.IMApplication.utils.NotificationUtils;
import com.jmu.edu.IMApplication.utils.WillowUtils;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.GetUserInfoCallback;
import cn.jpush.im.android.api.content.EventNotificationContent;
import cn.jpush.im.android.api.content.PromptContent;
import cn.jpush.im.android.api.content.TextContent;
import cn.jpush.im.android.api.event.ContactNotifyEvent;
import cn.jpush.im.android.api.event.MessageEvent;
import cn.jpush.im.android.api.event.NotificationClickEvent;
import cn.jpush.im.android.api.event.OfflineMessageEvent;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.Message;
import cn.jpush.im.android.api.model.UserInfo;

import static cn.jpush.im.android.api.event.ContactNotifyEvent.Type.contact_deleted;
import static cn.jpush.im.android.api.event.ContactNotifyEvent.Type.contact_updated_by_dev_api;


/**
 * 在demo中对于通知栏点击事件和在线消息接收事件，我们都直接在全局监听
 */
public class GlobalEventListener {
    private Context appContext;

    public GlobalEventListener(Context context) {
        appContext = context;
        initChannel();
        JMessageClient.registerEventReceiver(this, 2);
    }


    public void onEvent(@NotNull ContactNotifyEvent event) {
        showNotification(event);
        String reason = event.getReason();
        String username = event.getFromUsername();
        int state = 0;
        switch (event.getType()) {
            case invite_received:
                state = FriendUtils.RECEIVE;
                break;
            case invite_accepted:
                state = FriendUtils.AGREE;
                break;
            case invite_declined:
                state = FriendUtils.DISAGREE;
                break;
            default:
                break;
        }
        addData(username, reason, state);

        Log.d("好友监听", "收到了好友消息:" + username + "\n原因为:" + reason);
    }

    private void addData(String username, String reason, int state) {
        // 通过获取的数据，组装成好友通知类
        FriendInvite friendInvite = new FriendInvite();
        friendInvite.setFromUsername(username);
        friendInvite.setReason(reason);
        friendInvite.setStatus(state);
        friendInvite.setToUsername(MyApplication.getUser().getUserName());
        MyApplication.getFriendInviteList().add(friendInvite);
        EventBus.getDefault().post(new FriendNotificationRefresh(true));
    }

    //在线消息监听
    public void onEvent(@NotNull MessageEvent event) {
        showNotification(event.getMessage());
    }

    //离线消息监听
    public void onEvent(@NotNull OfflineMessageEvent event) {
        List<Message> msgs = event.getOfflineMessageList();
        for (Message msg : msgs) {
            showNotification(msg);
        }
    }

    public void onEvent(@NotNull NotificationClickEvent event) {
        //通知点击事件
        Log.d("test", "click: ");
    }

    private void showNotification(Message message) {
        NotificationManager notifyManager = NotificationUtils.getNotificationManager(appContext);
        NotificationCompat.Builder builder = NotificationUtils.getBuilder(appContext);

        //根据消息进行判断以获得通知的标题和内容
        String contentText = "";
        switch (message.getContentType()) {
            case text:
                TextContent textContent = (TextContent) message.getContent();
                contentText = textContent.getText();
                break;
            case image:
                contentText = "[图片]";
                break;
            case voice:
                contentText = "[语音消息]";
                break;
            case custom:
                contentText = "[定制消息]";
                break;
            case eventNotification:
                EventNotificationContent eventNotificationContent = (EventNotificationContent) message.getContent();
                switch (eventNotificationContent.getEventNotificationType()) {
                    case group_member_added:
                        //群成员加群事件
                        contentText = "群成员加群事件";
                        break;
                    case group_member_removed:
                        //群成员被踢事件
                        contentText = "群成员被踢事件";
                        break;
                    case group_member_exit:
                        //群成员退群事件
                        contentText = "群成员退群事件";
                        break;
                    case group_info_updated://since 2.2.1
                        //群信息变更事件
                        contentText = "群信息变更事件";
                        break;
                }
                break;
            case unknown:
                // 处理未知消息，未知消息的Content为PromptContent 默认提示文本为“当前版本不支持此类型消息，请更新sdk版本”，上层可选择不处理
                PromptContent promptContent = (PromptContent) message.getContent();
//                promptContent.getPromptType();//未知消息的type是unknown_msg_type
                contentText = promptContent.getPromptText();//提示文本，“当前版本不支持此类型消息，请更新sdk版本”
                break;
            default:
                contentText = "默认消息";
                break;
        }
        builder.setContentText(contentText);
        String contentTitle = "";
        Intent intent = new Intent(appContext, MainActivity.class);
        if (message.getFromUser() != null) {
            String username = message.getFromUser().getUserName();
            intent.putExtra("username", username);
            intent.putExtra("nickname", WillowUtils.getNickName(message.getFromUser()));
            intent.putExtra("destFrag", "chat");
            Conversation conversation = MsgUtils.getSingleConversation(username);
            contentTitle = username + "（" + conversation.getUnReadMsgCnt() + "条未读）";
        }
        builder.setContentTitle(contentTitle);
        //设置通知的点击Intent
        PendingIntent pIntent = PendingIntent.getActivity(appContext, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pIntent);
        Log.d("test", "showNotification: ");
        //显示通知
        notifyManager.notify(0, builder.build());
    }

    private void showNotification(ContactNotifyEvent event) {
        //两种不进行通知的事件
        if (event.getType() == contact_deleted || event.getType() == contact_updated_by_dev_api) {
            return;
        }
        NotificationManager notifyManager = NotificationUtils.getNotificationManager(appContext);
        NotificationCompat.Builder builder = NotificationUtils.getBuilder(appContext);
        String username = event.getFromUsername();
        String contentText = "";

        switch (event.getType()) {
            case invite_received://收到好友邀请
                contentText = username + " 请求添加您为好友";
                break;
            case invite_accepted://对方接收了你的好友邀请
                contentText = username + " 接受了您的好友请求";
                break;
            case invite_declined://对方拒绝了你的好友邀请
                contentText = username + " 拒绝了您的好友请求";
                break;
        }
        builder.setContentTitle("好友通知")
                .setContentText(contentText);
        Intent intent = new Intent(appContext, MainActivity.class);
        intent.putExtra("destFrag", "friendNotification");
        PendingIntent pIntent = PendingIntent.getActivity(appContext, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pIntent);
        Log.d("test", "showNotification: ");
        //显示通知
        notifyManager.notify(0, builder.build());
    }

    private void initChannel() {
        //对android 8进行适配
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel channel = new NotificationChannel("CHANNEL_ID", "name", importance);
            channel.setDescription("description");
            NotificationManager notificationManager = appContext.getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }
}
